﻿using System.Threading.Tasks;
using Microsoft.Live;
using Repository.MODELs;
using Repository.Repositories;
using Repository.Sync;
using Windows.Storage;

namespace Repository.LiveConnection
{
    public class LiveConnection
    {
        private LiveConnectClient _liveConnectClient;

        public static LiveConnection Instance
        {
            get
            {
                return Nested._instance;
            }
        }

        private class Nested
        {
            internal static readonly LiveConnection _instance = new LiveConnection();
        }

        /// <summary>
        /// Create connection with scope Basic, SkyDrive.
        /// </summary>
        /// <returns>Return true if connect successful. Otherwise, return false.</returns>
        private async Task<bool> CreateConnectionAsync()
        {
            try
            {
                var auth = new LiveAuthClient();
                var loginResult = await auth.LoginAsync(new[] { "wl.basic", "wl.contacts_skydrive", "wl.skydrive_update", "wl.emails", "wl.contacts_photos" });

                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    _liveConnectClient = new LiveConnectClient(loginResult.Session);

                    return true;
                }

                return false;
            }
            catch (LiveAuthException)
            {
                return true;
            }
        }

        private object _currentID;

        public async Task<LiveUserInformationModel> GetUserInformation()
        {
            try
            {
                if (_liveConnectClient == null) return null;

                dynamic userInfo = (await _liveConnectClient.GetAsync("me")).Result;

                if (userInfo == null)
                {
                    return null;
                }

                var userInfoModel = new LiveUserInformationModel
                                        {
                                            ID = userInfo.id,
                                            FullName = userInfo.name,
                                            FirstName = userInfo.first_name,
                                            LastName = userInfo.last_name,
                                            Link = userInfo.link,
                                            Email = userInfo.emails.preferred,
                                            Gender = userInfo.gender,
                                            Locale = userInfo.locale,
                                            UpdatedTime = userInfo.updated_time
                                        };

                _currentID = userInfoModel.ID;
                return userInfoModel;
            }
            catch
            {
                return null;
            }
        }

        public string GetUserAvatarUrl()
        {
            return string.Format("https://apis.live.net/v5.0/{0}/picture", _currentID);
        }

        public async Task<bool> Signin()
        {
            if (await CreateConnectionAsync())
            {
                if (GlobalData.UserInformationModel == null)
                {
                    GlobalData.UserInformationModel = await Instance.GetUserInformation();
                }

                if (GlobalData.UserInformationModel != null)
                {
                    ApplicationData.Current.LocalSettings.Values["UserFirstName"] = GlobalData.UserInformationModel.FirstName;
                    ApplicationData.Current.LocalSettings.Values["UserID"] = GlobalData.UserInformationModel.Email;
                    // Check existance of user on server
                    var cloudInfo = await UserInformationRepository.Instance.GetUser(ApplicationData.Current.LocalSettings.Values["UserID"] + string.Empty);

                    // If null profile is returned, create blank one for newcommer.
                    if (cloudInfo == null)
                    {
                        var newBlankInfo = new UserModel
                        {
                            DOB = null,
                            Email = "",
                            Phone = "",
                            Username = GlobalData.UserInformationModel.Email
                        };

                        await UserInformationRepository.Instance.AddUser(newBlankInfo);
                    }
                    else
                    {
                        GlobalData.MyUserID = cloudInfo.UserID;
                    }

                }
                else
                {
                    if (ApplicationData.Current.LocalSettings.Values["UserID"] + string.Empty != string.Empty)
                    {
                        var cloudInfo = await UserInformationRepository.Instance.GetUser(ApplicationData.Current.LocalSettings.Values["UserID"] + string.Empty);
                        GlobalData.MyUserID = cloudInfo.UserID;
                    }
                }

                return true;
            }

            return false;
        }
    }
}
